//
// Created by ASUS on 2024/5/4/星期六.
//

#include <bits/stdc++.h>
using namespace std;

class Bcj{
	int n;
	vector<int> fa,rank;
public:
	Bcj(int n):fa(n),rank(n){
		for(int i=0;i<n;i++){
			fa[i]=i;
			rank[i]=1;
		}
	}
	~Bcj(){}
	int find(int x){
		return fa[x]==x?x:fa[x]= find(fa[x]);
	}

	void merge(int i,int j){
		int x=find(i),y=find(j);
		if(rank[x]<=rank[y]) fa[x]=y;
		else fa[y]=x;
		if(rank[x]==rank[y]&&x!=y) rank[y]++;
	}
	int kind(){
		unordered_set<int> st;
		for(int x:fa) st.insert(find(x));
		return st.size();
	}
};

struct Edge{
	int u,v,w;
	Edge(int u,int v,int w):u(u),v(v),w(w){}
	bool operator < (const Edge& e) const{
		return w<e.w;
	}
};

int kruskal(vector<Edge> &edges,int n){
	long long count = 0, cost = 0; // 计数和花费
	Bcj bcj(n);
	sort(edges.begin(),edges.end());
	for (auto&edge: edges)  {
		int u = edge.u, v = edge.v, w = edge.w;
		int rootU = bcj.find(u), rootV = bcj.find(v);
		if (rootU != rootV) {
			bcj.merge(u, v);
			cost += w;
			count++;
		}
	}
	if (count < n - 1) cout<< -1; // 不连通
	else cout<<cost;
}